/*
 * Copyright 2019-2025 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * https://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.iiifi.kite.ribbon.predicate;

import java.util.Map;

import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.iiifi.kite.core.spring.SpringContextUtils;
import com.iiifi.kite.core.util.StringUtils;
import com.iiifi.kite.ribbon.KiteRibbonProperties;


/**
 * 基于 Metadata 的服务筛选
 *
 * @author kite@iiifi.com 花朝
 */
public class MetadataAwarePredicate extends DiscoveryEnabledPredicate {

    public static final MetadataAwarePredicate INSTANCE = new MetadataAwarePredicate();

    @Override
    protected boolean apply(NacosServer server) {
        final Map<String, String> metadata = server.getInstance().getMetadata();
        // 获取配置
        KiteRibbonProperties properties = SpringContextUtils.getBean(KiteRibbonProperties.class);
        // 服务里的配置
        String localTag = properties.getTag();

        if (StringUtils.isBlank(localTag)) {
            return true;
        }
        // 本地有 tag，服务没有，返回 false
        String metaDataTag = metadata.get("tag");
        if (StringUtils.isBlank(metaDataTag)) {
            return false;
        }
        return metaDataTag.equals(localTag);
    }

}
